package com.example.demo.service.impl;

import com.example.demo.constant.RedisKeyConstant;
import com.example.demo.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * key-value可以模拟的场景
 *
 * @author Code Farmer
 * @date 2020/5/8 13:27
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private ValueOperations<String, String> valueOperations;

    @Override
    public void addUser(String id, String name, int age) {
        valueOperations.set(String.format(RedisKeyConstant.USER_INFO, id, "name"), name);
        valueOperations.set(String.format(RedisKeyConstant.USER_INFO, id, "name"), id);
    }

    @Override
    public String getUserName(String id) {
        return Optional.ofNullable(
                valueOperations.get(String.format(RedisKeyConstant.USER_INFO, id, "name"))
        ).orElse(StringUtils.EMPTY);
    }

}
